package com.bzframework.pro.socket.configuration;

import com.bzframework.pro.authorize.token.manager.UserTokenManager;
import com.bzframework.pro.socket.WebSocketMessagingHandler;
import com.bzframework.pro.socket.manager.DefaultMessagingManager;
import com.bzframework.pro.socket.manager.MessagingManager;
import com.bzframework.pro.socket.provider.SubscriptionProvider;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;
import org.springframework.web.reactive.HandlerMapping;
import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping;
import org.springframework.web.reactive.socket.WebSocketHandler;
import org.springframework.web.reactive.socket.server.support.WebSocketHandlerAdapter;

import java.util.HashMap;
import java.util.Map;

@AutoConfiguration
public class WebSocketMessagingHandlerConfiguration {

    @Bean
    @ConditionalOnMissingBean(MessagingManager.class)
    public DefaultMessagingManager defaultMessagingManager(ObjectProvider<SubscriptionProvider> providers) {
        DefaultMessagingManager messagingManager = new DefaultMessagingManager();
        providers.forEach(messagingManager::register);
        return messagingManager;
    }

    @Bean
    public HandlerMapping webSocketMessagingHandlerMapping(MessagingManager messagingManager,
                                                           UserTokenManager userTokenManager) {
        WebSocketMessagingHandler messagingHandler = new WebSocketMessagingHandler(
            messagingManager,
            userTokenManager
        );
        final Map<String, WebSocketHandler> map = new HashMap<>(1);
        map.put("/messaging/**", messagingHandler);

        final SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
        mapping.setOrder(Ordered.HIGHEST_PRECEDENCE);
        mapping.setUrlMap(map);
        return mapping;
    }

    @Bean
    @ConditionalOnMissingBean
    public WebSocketHandlerAdapter webSocketHandlerAdapter() {
        return new WebSocketHandlerAdapter();
    }

}
